export const JsonMgr = {
    _datas: [],
    _loadList: [],

    getJson(jsonName) {
        return this._datas[jsonName];
    },

    addItem(jsonName) {
        if (G.utils.isInArr(jsonName, this._loadList)) {
            return;
        }
        this._loadList.push(jsonName);
    },

    startLoad(cb) {
        if (this._loadList.length <= 0) {
            cb && cb();
            return;
        }
        let name = this._loadList.pop();
        this.loadJson(name, () => {
            this.startLoad(cb);
        });
    },

    loadAllJsons(cb) {
        cc.loader.loadResDir('jsons', (err, assests) => {
            if (err) {
                console.log(err);
                return;
            }
            for (let i = 0; i < assests.length; i++) {
                let res = assests[i];
                this._datas[res._name] = this.parseData(res);
            }
            cb && cb();
        });
    },

    loadJson(jsonName, cb) {
        this._datas = this._datas || [];
        cc.loader.loadRes('jsons/' + jsonName, (err, res) => {
            if (err) {
                console.error(err)
                return;
            }
            this._datas[jsonName] = this.parseData(res);
            cb && cb();
        });
    },

    parseData(jsonAsset) {
        // cc.log(jsonAsset);
        if (!jsonAsset || !jsonAsset.json) {
            return;
        }
        const obj = jsonAsset.json;
        const data = obj.vals;
        const cols = obj.cols;
        // obj.vals = undefined;
        // obj.cols = undefined;

        const colCnt = cols.length;

        // 将数据转换成一个对象实例
        const instance = [];
        for (let i = 0; i < data.length; i++) {
            const item = data[i];
            let obj = {};
            for (let j = 0; j < colCnt; j++) {
                const colName = cols[j];
                obj[colName] = item[j];
            }
            instance.push(obj);
        }
        return instance;
    },
};